package com.example.swimmingpool.service.wx;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.example.swimmingpool.SwimmingPoolThreadLocal;
import com.example.swimmingpool.constants.RedisConstants;
import com.example.swimmingpool.entity.booking.Booking;
import com.example.swimmingpool.util.RedisUtil;
import com.example.swimmingpool.vo.wx.WxBookingVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class WxBookingService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private RedisUtil redisUtil;

    public Boolean booking(WxBookingVo vo){
        var userId = SwimmingPoolThreadLocal.getUserId();
        var redis = redisUtil.getRedis();
        var bookingTime = vo.getBookingTime();


        LocalDateTime date =  LocalDateTimeUtil.beginOfDay(LocalDateTimeUtil.parseDate(bookingTime,DatePattern.NORM_DATE_PATTERN).atStartOfDay());
        Duration between = LocalDateTimeUtil.between(LocalDateTimeUtil.now(), LocalDateTimeUtil.endOfDay(date));
        log.info(String.valueOf(LocalDateTimeUtil.endOfDay(date)));
        String key = RedisConstants.USER_BOOKING_KEY +bookingTime;
        redis.opsForList().leftPush(key, String.valueOf(userId));
        redis.expire(key,between);

        Booking booking = new Booking().setBookingTime(bookingTime)
                .setUserId(String.valueOf(userId))
                .setCreateTime( LocalDateTimeUtil.format(LocalDateTimeUtil.now(),DatePattern.NORM_DATETIME_PATTERN));
        mongoTemplate.insert(booking);
        return true;


    }

    public Long getPeopleCount(){
        String now = LocalDateTimeUtil.format(LocalDateTimeUtil.now(),DatePattern.NORM_DATE_PATTERN);
        String key = RedisConstants.USER_BOOKING_KEY + now;
        return redisUtil.getRedis().opsForList().size(key);

    }

    public List<Booking> getMyBooking(){
        var userId = SwimmingPoolThreadLocal.getUserId();
        Query query = new Query(Criteria.where("userId").is(userId+""));
        return mongoTemplate.find(query, Booking.class);


    }

    public Boolean isTodayBooking(){
        var today = LocalDateTimeUtil.format(LocalDateTimeUtil.now(),DatePattern.NORM_DATE_PATTERN);
        log.info(String.valueOf(getMyBooking()));
        return Optional.ofNullable(getMyBooking())
                .map(bookings -> bookings.stream().anyMatch(booking -> today.equals(booking.getBookingTime())))
                .orElse(false);


    }
}
